package services;

import dao.CommunityDao;
import dao.OrderDao;
import entity.CommunityInfo;
import entity.OrderInfo;
import openConn.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class BuyCommunityServices {
    public static void buyCommunity(int userId,int comId,int addressId,Double buyCount) throws SQLException {
        Connection connection = DruidUtils.openConn();
        connection.setAutoCommit(false);
        OrderInfo orderInfo = new OrderInfo(userId,comId,addressId,buyCount);
        OrderDao.insert(orderInfo,connection);
        CommunityInfo communityInfo = CommunityDao.selectById(comId);

        if (communityInfo.getComCount()-buyCount < 0){
            connection.rollback();
            System.out.println("库存不足，下单失败");
            System.out.println("请重新下单");
            System.out.println("-------------------------");
        }else {
            CommunityDao.update(comId,communityInfo.getComCount()-buyCount,connection);
            connection.commit();
            System.out.println("下单成功");
            System.out.println("欢迎继续下单");
            System.out.println("-------------------------");
        }
        connection.close();
    }
}
